/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ucab.desarrollo.viajesbook.persistencia;

import java.io.Serializable;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

/**
 *
 * @author isak
 */
public abstract class AbstractHibernateDAO<DomainObject extends Serializable, KeyType extends Serializable> extends HibernateDaoSupport {

protected abstract Class<DomainObject> getDomainClass();

protected Class<DomainObject> domainClass = getDomainClass();


    public DomainObject buscar(KeyType id)
    {        
        
        return (DomainObject)getHibernateTemplate().load(getDomainClass(), id);
    }


    public Session obtenerSesion()
    {
        return getHibernateTemplate().getSessionFactory().getCurrentSession();
    }

    public void actualizar(DomainObject object)
    {
        getHibernateTemplate().merge(object);
    }

    public void salvar(DomainObject object)
    {
        getHibernateTemplate().saveOrUpdate(object);
    }

    public void borrar(DomainObject object)
    {
        getHibernateTemplate().delete(object);
    }
    
    public void borrarPorId(KeyType id)
    {
        Object obj = buscar(id);
        getHibernateTemplate().delete(obj);
    }



    public List<DomainObject> obtenerLista(){
        return (getHibernateTemplate().find("from " + domainClass.getName() + " o"));
    }

   
    public void borrarTodos()
    {
         getHibernateTemplate().execute(new HibernateCallback()
         {
             public Object doInHibernate(Session session) throws HibernateException {
                 String hqlDelete = "delete " + domainClass.getName();
                 int deletedEntities = session.createQuery(hqlDelete).executeUpdate();
                 return null;
             }

         });

    }

    public int cantidadElementos()
    {
        List list = getHibernateTemplate().find(
                "select count(*) from " + domainClass.getName() + " o");
        Integer count = (Integer) list.get(0);
        return count.intValue();
    }

}
